package com.baike.controller;

import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import com.baike.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/login")
@Api(value = "运营用户登录接口")
@RefreshScope
public class LoginController {

    @ApiOperation("运营用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uname",value = "用户账户",required = true,paramType = "path"),
            @ApiImplicitParam(name = "pwd",value = "用户密码",required = true,paramType = "path")
    })
    @GetMapping("/{uname}/{pwd}")
    public Result loginInfo(@PathVariable("uname")String uname,@PathVariable("pwd")String pwd){
        // 使用 shiro 的登录功能
        // 1. 需要获取 subject 对象
        Subject subject = SecurityUtils.getSubject();
        // 2. 将账号 密码封装成 token 对象
        UsernamePasswordToken token = new UsernamePasswordToken(uname,pwd);
        // 3. 调用subject的login方法执行登录逻辑
        // 我们方法调用的时候,被调用的方法如何如何告诉我们 执行的功能是否成功
        // 1.返回值(最常用)  2.通过抛异常的方式
        // shiro 使用的就是抛异常的方式
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            return Result.build(ConstantEnum.UNKNOWN).setResult("此账户不存在");
        }catch (IncorrectCredentialsException e){
            return Result.build(ConstantEnum.INCORRECT);
        }
        
        User user = (User) subject.getPrincipal();
        return Result.build(ConstantEnum.SUCCESS).setResult("登录成功");
    }

    @ApiOperation("无权限调用方法")
    @GetMapping("/unauthorized")
    public Result unauthorized (){
        return Result.build(ConstantEnum.ERROR).setResult("抱歉无权限访问国家机密");
    }

    @ApiOperation("无权限调用方法")
    @GetMapping("/unauthorizeds")
    public Result unauthorizeds (){
        return Result.build(ConstantEnum.ERROR).setResult("抱歉,此处需要登录访问");
    }
}
